package com.echoesnet.echoesshortvideo.Activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.VideoUtilListener;
import com.echoesnet.echoesshortvideo.Utils.VideoUtils;
import com.echoesnet.echoesshortvideo.views.MyProgressDialog;
import com.echoesnet.echoesshortvideo.views.video.EmptyControlVideo;
import com.echoesnet.echoesshortvideo.views.video.ThumbnailAdapter;
import com.echoesnet.echoesshortvideo.views.video.ThumbnailView;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;
import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * 视频时长剪切
 */
public class CutTimeActivity extends BaseActivity
{

    @BindView(R.id.video_view)
    public EmptyControlVideo mVideoView;
    @BindView(R.id.ll_thumbnail)
    public LinearLayout llThumbnail;
    @BindView(R.id.rv_thumbnail)
    public RecyclerView rvThumbnail;
    @BindView(R.id.thumbnailView)
    public ThumbnailView thumbnailView;
    @BindView(R.id.tv_finish_video)
    public TextView tvFinishVideo;
    @BindView(R.id.rl_video)
    public RelativeLayout rlVideo;
    @BindView(R.id.rl_thumb)
    public RelativeLayout rlThumb;
    @BindView(R.id.rl_thumbnail_view)
    public RelativeLayout rlThumbnailView;
    @BindView(R.id.rl_finish)
    public RelativeLayout rlFinish;
    @BindView(R.id.img_thumb)
    public ImageView imgThumb;
    @BindView(R.id.tv_select_time)
    public TextView tvSelectTime;


    private final String TAG = CutTimeActivity.class.getSimpleName();
    /**
     * 视频宽度
     */
    public static int VIDEO_WIDTH = 1280;
    /**
     * 视频高度
     */
    public static int VIDEO_HEIGHT = 720;
    private String mVideoPath;

    private int videoWidth;
    private int videoHeight;

    private int videoDuration;
    private Activity mAct;
    private long startTime = 0;
    private long endTime;
    private int windowWidth;
    private int windowHeight;
    private float itemWidth;
    private int minDuration = 15000;
    private ThumbnailAdapter thumbnailAdapter;
    private MyProgressDialog pDialog;
    private float rotation = 0;
    private List<String> imgPathList;
    private int frameNum;
    private float itemTime = minDuration/6.5f;
    private int firstVisibleItem;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cut_time);

        ButterKnife.bind(this);
        mAct = this;
        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra("path");
        Logger.t(TAG).d("mVideoPath>>>>>>>>>>" + mVideoPath);
        windowWidth = getWindowManager().getDefaultDisplay().getWidth();
        windowHeight = getWindowManager().getDefaultDisplay().getHeight();
        MediaMetadataRetriever retr = new MediaMetadataRetriever();
        retr.setDataSource(mVideoPath);
        try
        {
            rotation = Float.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
            videoDuration = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
            videoHeight = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
            videoWidth = Integer.valueOf(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
            if (rotation == 90 || rotation == 270)
            {
                int temp = videoWidth;
                videoWidth = videoHeight;
                videoHeight = temp;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        imgPathList = new ArrayList<>();
        itemWidth = windowWidth / 8.5f;
        Logger.t(TAG).d("rotation>>" + rotation + "|videoDuration>>" + videoDuration+ "|itemWidth>>" + itemWidth);
        thumbnailAdapter = new ThumbnailAdapter(mAct, mVideoPath, itemWidth, rotation, imgPathList);
        initUI();
        try
        {
            FFmpeg.getInstance(mAct).loadBinary(new LoadBinaryResponseHandler());
        } catch (FFmpegNotSupportedException e)
        {
            e.printStackTrace();
        }
    }

    private void initUI()
    {
        VideoOptionModel videoOptionModel = new VideoOptionModel(tv.danmaku.ijk.media.player.IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
        VideoOptionModel videoOptionModel1 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 5);
        List<VideoOptionModel> list = new ArrayList<>();
        list.add(videoOptionModel);
        list.add(videoOptionModel1);
        GSYVideoManager.instance().setOptionModelList(list);
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT);
        mVideoView.setVideoAllCallBack(new GSYSampleCallBack()
        {
            @Override
            public void onPlayError(String url, Object... objects)
            {
                super.onPlayError(url, objects);
                Logger.t(TAG).d("onPlayError>>>>>>>>>>>>>>>");
            }

            @Override
            public void onPrepared(String url, Object... objects)
            {
                super.onPrepared(url, objects);
                Logger.t(TAG).d("prepared>>>>>>>>>>>>>>>");
            }

            @Override
            public void onStartPrepared(String url, Object... objects)
            {
                super.onStartPrepared(url, objects);
                Logger.t(TAG).d("onStartPrepared>>>>>>>>>>>>>>>");
            }

            @Override
            public void onAutoComplete(String url, Object... objects)
            {
                super.onAutoComplete(url, objects);
//                mVideoView.setSeekOnStart(startTime);
//                mVideoView.startPlayLogic();
            }
        });
        mVideoView.setLooping(true);
        mVideoView.setUp(mVideoPath, false, null);
        mVideoView.startPlayLogic();
        if (videoDuration >= (minDuration + 1000))
            initThumbs();
        else
        {
            rlThumbnailView.setVisibility(View.GONE);
            tvSelectTime.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onResume()
    {
        if (mVideoView != null)
            mVideoView.onVideoResume(false);
        super.onResume();
    }

    @Override
    protected void onPause()
    {
        if (mVideoView != null)
            mVideoView.onVideoPause();
        super.onPause();
    }

    @Override
    protected void onStop()
    {
        if (mVideoView != null)
            mVideoView.onVideoPause();
        super.onStop();
    }

    private void changeVideoPlay()
    {
        View item = rvThumbnail.findChildViewUnder(thumbnailView.getLeftInterval(),thumbnailView.getTopInterval());
        int position = rvThumbnail.getChildLayoutPosition(item);
        position = position > 0?position:0;
        if (item == null)
            return;
        Rect rect = new Rect();
        item.getLocalVisibleRect(rect);
        Logger.t(TAG).d("开始item 位置 position >>" + position + "| left >>" + item.getLeft()+ "| right >>" + item.getRight()+ "| top >>" + item.getTop()+ "| bottom >>" + item.getBottom());
        Logger.t(TAG).d("开始位置 getLeftInterval >>" + thumbnailView.getLeftInterval()+ " getTopInterval >>" + thumbnailView.getTopInterval());
        float rvWidth = itemWidth * frameNum;
        itemTime = videoDuration/rvWidth;
        startTime = (int) ((videoDuration/rvWidth) * (position * itemWidth +thumbnailView.getLeftInterval() - item.getLeft()));
        float cutTime = itemTime * (thumbnailView.getEndRightInterval() - thumbnailView.getLeftInterval());
        cutTime = cutTime > 15000 ?15000:cutTime;
        endTime = (long) (startTime + cutTime);
        tvSelectTime.setText(String.format("已选择%ss" , (int)((endTime - startTime)/1000)));
        Logger.t(TAG).d("startTime>" + startTime + "|endTime>" + endTime + "|cutTime>" + cutTime);
        if (mVideoView != null)
        {
            mVideoView.seekTo(startTime);
            thumbnailView.start();
        }
    }

    /**
     * 剪切视频
     */
    private void cutVideo()
    {
        if (mVideoView != null)
            mVideoView.onVideoPause();
        View item = rvThumbnail.findChildViewUnder(thumbnailView.getLeftInterval(),thumbnailView.getTopInterval());
        int position = rvThumbnail.getChildLayoutPosition(item);
        position = position > 0?position:0;
        if (item == null)
            return;
        Rect rect = new Rect();
        item.getLocalVisibleRect(rect);
        float rvWidth = itemWidth * frameNum;
        itemTime = videoDuration/rvWidth;
        startTime = (int) ((videoDuration/rvWidth) * (position * itemWidth +thumbnailView.getLeftInterval() - item.getLeft()));
        float cutTime = itemTime * (thumbnailView.getEndRightInterval() - thumbnailView.getLeftInterval());
        cutTime = cutTime > 15000 ?15000:cutTime;
        endTime = (long) (startTime + cutTime);
        Logger.t(TAG).d("startTime>>" + startTime + "|endStr>>>" + endTime);
        long startM = startTime / 1000;
        long endM = (endTime - startTime) / 1000;
        Logger.t(TAG).d("startM = " + startM + "|endM = " + endM + "|");
        String startStr;
        String endStr;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        startStr = simpleDateFormat.format(new Date(startTime));

        if (endM < 10)
        {
            endStr = "00:00:0" + endM;
        } else
        {
            endStr = "00:00:" + endM;
        }
        Logger.t(TAG).d("startStr>>" + startStr + "|endStr>>>" + endStr);
        String showType = videoWidth > videoHeight ? "0" : "1";
        Intent intent = new Intent(mAct,PublishVideoAct.class);
        intent.putExtra("path",mVideoPath);
        intent.putExtra("startTime",startStr);
        intent.putExtra("endTime",endStr);
        intent.putExtra("showType", showType);
        startActivity(intent);
        setResult(RESULT_OK);
        finish();
    }



    /**
     * 初始化缩略图
     */
    private void initThumbs()
    {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mAct, LinearLayoutManager.HORIZONTAL, false);
        rvThumbnail.setLayoutManager(linearLayoutManager);
        rvThumbnail.setAdapter(thumbnailAdapter);
        frameNum = (int) (videoDuration / itemTime);
        final int frameTime = 1000;
        Logger.t(TAG).d("frame>>>>>>>>>" + frameNum);
        thumbnailAdapter.setFrameCount(frameNum);
        thumbnailAdapter.setFrameTime(itemTime);
        thumbnailAdapter.notifyDataSetChanged();
        thumbnailView.setMinInterval(itemWidth,itemWidth * frameNum);
        Logger.t(TAG).d("initThumbs>>>>" + (itemWidth * frameNum) + "| >>>>" + thumbnailView.getEndRightInterval());
        thumbnailView.start();
        thumbnailView.setOnScrollBorderListener(new ThumbnailView.OnScrollBorderListener()
        {
            @Override
            public void OnScrollBorder(float start, float end)
            {

            }

            @Override
            public void onScrollStateChange()
            {
                changeVideoPlay();
            }

            @Override
            public void complete()
            {
                if (mVideoView != null)
                {
                    Logger.t(TAG).d("seekTo>>>" + startTime);
                    if (startTime == 0)
                        mVideoView.startPlayLogic();
                    else
                    {
                        mVideoView.seekTo(startTime);
                        mVideoView.setSeekOnStart(startTime);
                    }

                }
            }
        });
        rvThumbnail.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)
            {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState)
                {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        changeVideoPlay();
                        break;
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
                super.onScrolled(recyclerView, dx, dy);
//                //   只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
//                LinearLayoutManager linearManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                //获取最后一个可见view的位置
//                int lastVisibleItem = linearManager.findLastVisibleItemPosition();
//                //获取第一个可见view的位置
//                firstVisibleItem = linearManager.findFirstVisibleItemPosition();
//                Logger.t(TAG).d("firstVisibleItem > " + firstVisibleItem + "| lastVisibleItem" + lastVisibleItem);
            }
        });
    }

    @OnClick({R.id.img_play, R.id.tv_cancel, R.id.tv_finish_video})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.img_play:

                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_finish_video:
                if (videoDuration >= (minDuration + 1000))
                {
                    cutVideo();
                }else
                {
                    Intent intent = new Intent(mAct,PublishVideoAct.class);
                    intent.putExtra("path",mVideoPath);
//                    intent.putExtra("thumbnailPath",mVideoPath);
//                    intent.putExtra("showType", showType);
                    startActivity(intent);
                    setResult(RESULT_OK);
                    finish();
                }
                break;
        }
    }

    @Override
    protected void onDestroy()
    {
        if (mVideoView != null)
        {
            mVideoView.release();
        }
        super.onDestroy();
    }
}
